﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElectronicRecords.Models;
using System.Web.Security;

namespace ElectronicRecords.Controllers
{
    public class RequestsController : Controller
    {
        //
        // GET: /Requests/
        private DataManager _dataManager;
        public RequestsController(DataManager dataManager)
        {
            _dataManager = dataManager;
        }
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetFormFor(int id)
        {
            if (id == 1)
            {
                //запись на процедуру
                //получить весь список процедур
                List<Procedurs> l = _dataManager.Procedurs.GetAllProcedurs().ToList();

                List<SelectListItem> procedurs = new List<SelectListItem>();
                foreach (Procedurs p in l)
                {
                    procedurs.Add(new SelectListItem { Value = p.ID_Procedure.ToString(), Text = p.Name });
                }
                ViewData["Proced"] = procedurs;
                return PartialView("FormProc");
            }
            else
            {
                //запись к специалисту
                List<Specialists> l = _dataManager.Specialists.GetSpecialists().ToList();
                List<SelectListItem> specialists = new List<SelectListItem>();
                foreach (Specialists s in l)
                {
                    specialists.Add(new SelectListItem {Value=s.ID_Specialist.ToString(),Text=s.Firstname+" "+s.Lastname });
                }

                ViewData["Special"] = specialists;

                return PartialView("FormSpec");
            }
        }

        public ActionResult GetSpecByProc(int id)
        {

            Procedurs p = _dataManager.Procedurs.GetProcedure(id);
            List<Procedure_Specialist_XREF> l = p.Procedure_Specialist_XREF.ToList();

            List<Specialists> ls = new List<Specialists>();
            foreach (Procedure_Specialist_XREF ps in l)
            {
                ls.Add(ps.Specialists);
            }
            ViewData["Spec"] = ls;
            ViewData["Id"] = id;
            return PartialView();
        }

        public ActionResult GetProcBySpec(int id)
        {
            Specialists s = _dataManager.Specialists.GetSpecialist(id);
            List<Procedure_Specialist_XREF> l = s.Procedure_Specialist_XREF.ToList();

            List<Procedurs> lp = new List<Procedurs>();
            foreach (Procedure_Specialist_XREF ps in l)
            {
                lp.Add(ps.Procedurs);
            }
            ViewData["Proc"] = lp;
            ViewData["id"] = id;
            return PartialView();
        }

        public ActionResult GetBigTable(int proc, int spec,DateTime d)
        {
            ViewData["procid"] = _dataManager.Procedurs.GetProcedure(proc);
            ViewData["specid"] = _dataManager.Specialists.GetSpecialist(spec);;
            //получаем набор расписаний на эту неделю
           
            
            int i = (int)d.DayOfWeek;
            DateTime beg = d - (new TimeSpan(i - 1, 0, 0, 0));
            DateTime end = d + (new TimeSpan(7 - i, 0, 0, 0));
            beg = new DateTime(beg.Year, beg.Month, beg.Day, 0, 0, 0);
            end = new DateTime(end.Year, end.Month, end.Day, 23, 59, 59);
            ViewData["date_begin"] = beg;
            ViewData["date_end"] = end;
            
            List<Shedules> s = _dataManager.Specialists.GetShedulesBetweenDate(spec, beg, end).ToList();

            //получаем уже готовые заявки на эту неделю НУЖНОГО НАМ СПЕЦИАЛИСТА
            
            List<Requests> r = _dataManager.Requests.GetRequestsBetweenDateBySpec(beg, end,spec).ToList(); ;
            
            ViewRequestMap map = new ViewRequestMap();
            //просматриваем заявки
            DateTime currentdate;
            for ( i = 0; i < 7; i++)
            {
                //считаем дату
                currentdate= new DateTime(beg.Year,beg.Month,beg.Day,8,0,0);
                currentdate=currentdate + new TimeSpan(i, 0, 0, 0);
                for (int j = 0; j < 26; j++)
                {
                    //считаем дату ячейки
                    
                    //корректируем с раписанием работы специалиста
                    foreach (Shedules ss in s)
                    {
                        if (DateTime.Compare(ss.Date_Begin, currentdate) <= 0 && DateTime.Compare(ss.Date_End, currentdate)>0) map.Days[i][j] = 0;
                    }

                    //корректируем с уже созданными заявками
                    foreach (Requests rr in r)
                    {
                        if (DateTime.Compare(rr.DateRequest, currentdate) == 0 && map.Days[i][j] == 0) map.Days[i][j] = rr.ID_Request;
                    }

                   //корректируем с продолжительностью процедуры (не реализовано)
                   //корректируем с бронью (не реализовано)
                    currentdate = currentdate + new TimeSpan(0, 30, 0);
                }
            }
            ViewData["Shedules"] = s;
            ViewData["Requests"] = r;

            ViewData["Maps"] = map;
            return PartialView();
        }

        public ActionResult CreateRequest(int proc, int spec, DateTime date,DateTime time)
        {
            ViewData["procid"]=proc;
            ViewData["specid"]=spec;
            ViewData["date"]=date;
            ViewData["time"] = time;


            return PartialView();
        }

        public ActionResult FindClient(string searchStr, int proc, int spec, DateTime date, DateTime time)
        {
            List<Clients> l = _dataManager.Clients.FindClients(searchStr).ToList<Clients>();
            ViewData["Clients"] = l;
            ViewData["procid"] = proc;
            ViewData["specid"] = spec;
            ViewData["date"] = date;
            ViewData["time"] = time;
            return PartialView();
        }
        
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Create(int proc,int spec,DateTime date, DateTime time, int clientid)
        {
            Procedurs p = _dataManager.Procedurs.GetProcedure(proc);
            ViewData["proc"] = _dataManager.Procedurs.GetProcedure(proc);
            ViewData["spec"] = _dataManager.Specialists.GetSpecialist(spec);
            ViewData["date"] = date;
            ViewData["time"] = time;
            ViewData["client"] = _dataManager.Clients.GetClient(clientid);
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(int proc, int spec, DateTime date, DateTime time, int client,int confirm)
        {
            Requests r=new Requests();
            r.ID_Client = client;
            //найдем нужную процедуру специалиста
            List<Procedure_Specialist_XREF> lps = _dataManager.Specialists.GetServices(spec).ToList();
            foreach (Procedure_Specialist_XREF ps in lps) if (ps.ID_PROCEDURE == proc) r.ID_ProcedureOfSpecialist = ps.ID_PROCEDURESPECIALIST;
            r.DateRequest = new DateTime(date.Year, date.Month, date.Day, time.Hour, time.Minute,0);
            MembershipUser u = Membership.GetUser(User.Identity.Name);
            r.CreatedBy = (Guid)u.ProviderUserKey;
            _dataManager.Requests.CreateRequest(r);
            return View("OK");
        }


    }
}
